package safrain.nodelet.pool.reseter;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;

import safrain.nodelet.structure.FieldInfo;

/**
 * 这个Reseter是专门用于重置集合类型的（Collection，Map），不是把他们置Null，而是调用clear方法
 * 
 * @author safrain
 * 
 */
public class CollectionReseter implements IReseter {

	/**
	 * 集合的类型
	 */
	private CollectionType collectionType;

	/**
	 * 重置的field
	 */
	private Field field;

	@Override
	public void init(FieldInfo fieldInfo) {
		field = fieldInfo.field;
		if (isMap(field)) {
			collectionType = CollectionType.JAVA_UTIL_MAP;
		} else if (isCollection(field)) {
			collectionType = CollectionType.JAVA_UTIL_COLLECTION;
		}
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void reset(Object object) {
		try {
			Object valueObject = field.get(object);
			if (valueObject == null)
				return;
			if (collectionType == CollectionType.JAVA_UTIL_COLLECTION) {
				Collection collection = (Collection) valueObject;
				collection.clear();
			} else if (collectionType == CollectionType.JAVA_UTIL_MAP) {
				Map map = (Map) valueObject;
				map.clear();
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private boolean isMap(Field field) {
		return Map.class.isAssignableFrom(field.getType());
	}

	private boolean isCollection(Field field) {
		return Collection.class.isAssignableFrom(field.getType());
	}

	private enum CollectionType {
		JAVA_UTIL_MAP, JAVA_UTIL_COLLECTION
	}
}
